/*
 * @Author: rxn 1003312535@qq.com
 * @Date: 2023-10-07 14:13:21
 * @LastEditors: rxn 1003312535@qq.com
 * @LastEditTime: 2024-10-10 09:29:44
 * @FilePath: \vue3-progect\src\router\guard\permissionGuard.ts
 * @Description: 路由守卫
 */

//-tab 切换功能
import useTabSetting from "@/hook/setting/useTabSetting";

//- 枚举
import { PageEnum } from "@/enums/pageEnum";
//- 动态 router功能
import { addRoutes } from "@/router/routerHooks";
//- Store
import { useUser } from "@/store/modules/user";
import { useMenuStore } from "@/store/modules/menu";
import pinia from "@/store/store";

/**
 * 权限守卫
 */
export const createPermissionGuard = (router) => {
	let userInfoStore = useUser();
	const { changeTab } = useTabSetting();

	router.beforeEach(async (to, from) => {
		console.log("router.beforEach");
		//登录状态
		if (userInfoStore.getUserInfo.userId) {
			// 动态路由调用
			routerHandler(router);
			console.log(
				"router.getRoutes():",
				router.getRoutes(),
				"router.beforEach:",
				from,
				to
			);
			console.log("router.hasRoute(to.name)", router.hasRoute(to.name));
			if (router.hasRoute(to.name)) {
				changeTab(to);
			} else {
				return to.fullPath;
			}
		} else {
			//非登录状态/非首页-跳转首页/是首页直接跳转
			if (to.path != PageEnum.BASE_LOGIN) {
				return { path: PageEnum.BASE_LOGIN, replace: true };
			}
		}
	});
};
/**
 * 动态添加路由
 */
const routerHandler = async (router) => {
	const menuStore = useMenuStore(pinia);
	let routesList = menuStore.getAllMenu;
	//动态路由存在且重新加载
	if (routesList && menuStore.isFirstAdd) {
		addRoutes(router, routesList);
		menuStore.isFirstAdd = false;
	}
};
